<template>
  <button id="btn" @click="clearMarker">清除标注</button>
  <div id="map"></div>
  <div id="mouse-position">经度: {{ lng }}, 纬度:{{ lat }}</div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'


// 导入leaflet.pm和样式
import 'leaflet.pm';
import 'leaflet.pm/dist/leaflet.pm.css'

//导入axios
import axios from 'axios';

//导入钦州市JSON数据
import data from '@/data/钦州市.json'
let layersGroup
let lng = ref(0)//经度
let lat = ref(0)//纬度
//清除标注
function clearMarker() {
  if (layersGroup) {
    layersGroup.clearLayers();
  }
}



onMounted(() => {
  const map = L.map('map', {
    center: { lon: 109, lat: 22 },
    zoom: 10,
    attributionControl: false, //去掉右下角logo
    doubleClickZoom: false, // 禁用双击放大
  });
  /* 创建图层管理器 -- 集中管理图层 */
  layersGroup = new L.FeatureGroup();
  map.addLayer(layersGroup);

  let baseLayers = {
    '天地图影像': L.tileLayer("http://t0.tianditu.gov.cn/img_w/wmts?" +
      "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
      "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
      "&tk=6844ebdca6127c6a69fe4c575776e6a1", {
      maxZoom: 18,

    }),

    "天地图矢量": L.tileLayer("http://t0.tianditu.gov.cn/vec_w/wmts?" +
      "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
      "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
      "&tk=6844ebdca6127c6a69fe4c575776e6a1", {
      maxZoom: 18
    }).addTo(map),

    "OSM": L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 18
    }),

    "高德": L.tileLayer('https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', {
      maxZoom: 18
    }),
  };

  L.control.layers(baseLayers, {}, {
    position: 'topright',
    collapsed: true
  }).addTo(map);


  // 标记功能
  let markerIcon = L.icon({
    iconUrl: "https://unpkg.com/leaflet@1.9.3/dist/images/marker-icon.png",
    iconSize: [20, 30],
  });

  L.marker([21.897881, 108.61337], { icon: markerIcon })
    .addTo(map)
    .bindPopup("北部湾大学")
    .openPopup()
  // .remove()删除图层



  // #点击标记事件 
  map.on('dblclick', function (e) {
    // console.log(e.latlng.lat, e.latlng.lng)
    let marker = L.marker([e.latlng.lat, e.latlng.lng], { icon: markerIcon })
      .addTo(map)
      .bindPopup("新增标记点")
      .openPopup()
    layersGroup.addLayer(marker);
  })

  // 添加绘制工具功能
  map.pm.setLang('zh')
  map.pm.addControls({
    position: "topleft",
    drawPolygon: true, //绘制多边形
    drawMarker: false, //绘制标记点
    drawCircleMarker: false, //绘制圆形标记
    drawPolyline: true, //绘制线条
    drawRectangle: true, //绘制矩形
    drawCircle: true, //绘制圆圈
    editMode: true, //编辑多边形
    dragMode: true, //拖动多边形
    cutPolygon: true, //添加⼀个按钮以删除多边形⾥⾯的部分内容
    removalMode: true, //清除多边形
  })

  let options = {
    //定义用于临时绘制的样式（例如多边形的边线）
    templineStyle: {
      color: "red",
    },
    // 提⽰线从最后⼀个标记到⿏标光标的线虚线
    hintlineStyle: {
      color: "red",
      dashArray: [5, 5],
    },
    //用于设置最终绘制图形的样式
    pathOptions: {
      color: "orange",
      fillColor: "green",
    },
  }
  // 激活绘制绘制多边形和圆形时的样式
  map.pm.enableDraw("Polygon", options)
  map.pm.enableDraw("Circle", options)
  map.pm.disableDraw()

  //加载datav,获取JSON API
  // async function init() {
  //   try {
  //     let { data } = await axios.get("https://geo.datav.aliyun.com/areas_v3/bound/450700_full.json");
  //     console.log(data)
  //     let QinzhouLayer = L.geoJSON(data);
  //     map.addLayer(QinzhouLayer);
  //     QinzhouLayer.on("click", e => {
  //       let feature = e.layer.feature.properties.name;
  //       L.popup().setLatLng(e.latlng).setContent(feature).openOn(map);
  //       QinzhouLayer.setStyle({ color: "#3388FF" });
  //       e.layer.setStyle({ color: "#ff2d51" });
  //     });
  //   } catch (error) {
  //     console.error("数据加载失败", error);
  //     alert("数据加载失败，请稍后重试！");
  //   }
  // }
  // init()


  //使用JSON数据加载


  let QinzhouLayer = L.geoJSON(data);
  map.addLayer(QinzhouLayer);
  QinzhouLayer.on("click", e => {
    let feature = e.layer.feature.properties.name;
    L.popup().setLatLng(e.latlng).setContent(feature).openOn(map);
    QinzhouLayer.setStyle({ color: "#3388FF" });
    e.layer.setStyle({ color: "#ff2d51" });
  })





  //增加比例尺
  L.control.scale().addTo(map);


  map.locate({ setView: true, maxZoom: 16 });
  map.on('locationfound', function (e) {
    L.marker(e.latlng).addTo(map).bindPopup("您的位置").openPopup();
  });

  map.on('mousemove', function (e) {
    const latlng = e.latlng;
    // 同时更新页面上的鼠标位置
    lng.value = latlng.lng.toFixed(6)
    lat.value = latlng.lat.toFixed(6)
  });


})


</script>

<style scoped>
#map {
  height: 92vh;
  width: 100%;
}

#btn {
  position: fixed;
  z-index: 1000;
  top: 200px;
  right: 20px;
  padding: 10px 20px;
  background: linear-gradient(45deg, #ff7e5f, #feb47b);
  /* 渐变背景 */
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  border: none;
  border-radius: 8px;
  /* 圆角 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  /* 阴影 */
  cursor: pointer;
  transition: all 0.3s ease;
  /* 动画效果 */
}

#btn:hover {
  background: linear-gradient(45deg, #feb47b, #ff7e5f);
  /* 悬停时反转渐变 */
  transform: scale(1.1);
  /* 放大效果 */
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.2);
  /* 增强阴影 */
}

#btn:active {
  transform: scale(1.05);
  /* 点击时轻微缩放 */
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2);
  /* 阴影减弱 */
}

#mouse-position {
  position: fixed;
  z-index: 1000;
  bottom: 10px;
  left: 100px;
  background: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
</style>